#include "TestLittle.h"
#include <TFile.h>
#include <TTree.h>
#include <TRandom.h>
#include <iostream>
using namespace std;
TestLittle::TestLittle()
{
}
void TestLittle::SynchronousBetweenCloneTree()
{

    const char *filename = "../data/test.root";

    // ===================================================================
    // Part 1: 正确地创建并写入 ROOT 文件
    // ===================================================================
    cout << "Part 1: Writing data to " << filename << endl;

    // 使用智能指针或栈对象管理是更好的实践，但我们这里遵循原始 new/delete 风格
    TFile *file_write = new TFile(filename, "RECREATE");
    TTree *tree_write = new TTree("tree", "tree with random data");
    TRandom *random = new TRandom();

    double x, y;
    // 正确地将分支链接到 tree_write
    tree_write->Branch("x", &x, "x/D");
    tree_write->Branch("y", &y, "y/D");

    const int n_events = 100000;
    for (int i = 0; i < n_events; i++)
    {
        x = random->Gaus(0, 1);
        y = random->Gaus(1, 1);
        // *** 核心修复：必须调用 Fill() 来保存每一条记录 ***
        tree_write->Fill();
    }
    tree_write->Write();
    // 写入文件，关闭，然后删除 TFile 对象。
    // ROOT 会负责清理属于该文件的 tree_write 对象。
    // file_write->Write();
    // file_write->Close();
    // delete file_write;
    // delete random; // 单独创建的 TRandom 需要手动删除

    cout << "Part 1: Finished writing." << endl;
    //      << endl;

    // // ===================================================================
    // // Part 2: 重新打开文件，克隆 TTree，并读取数据
    // // ===================================================================
    cout << "Part 2: Reading and cloning data from " << filename << endl;

    // TFile *file_read = new TFile(filename, "READ");
    // if (file_read->IsZombie())
    // {
    //     cout << "Error opening file " << filename << endl;
    //     return;
    // }

    // *** 正确的做法：从打开的文件中获取 TTree 对象 ***
    // TTree *originalTree;
    // file_read->GetObject("tree", originalTree);
    // if (!originalTree)
    // {
    //     cout << "Could not find TTree named 'tree' in the file." << endl;
    //     file_read->Close();
    //     delete file_read;
    //     return;
    // }

    // file_read->cd();
    // // *** 在一个有效的 originalTree 对象上进行克隆 ***
    // // CloneTree() 不带参数会克隆所有记录
    TTree *cloneTree = tree_write->CloneTree(0);

    int entries = tree_write->GetEntries();
    cout << "Cloned tree has " << entries << " entries." << endl;

    double x_clone, y_clone;
    // cloneTree->SetBranchAddress("x", &x_clone);
    // cloneTree->SetBranchAddress("y", &y_clone);

    // 演示读取克隆树的前5个条目
    cout << "Reading first 5 entries from the cloned tree:" << endl;
    for (int i = 0; i < 5 && i < entries; i++)
    {
        tree_write->GetEntry(i);
        cout << "Entry " << i << ": x_clone = " << x_clone << ", y_clone = " << y_clone << "x= " << x << " y= " << y << endl;
        cloneTree->Fill();
    }

    cloneTree->Write();
    file_write->Close();
    // 清理

    // cloneTree 会随着 file_read 被删除
}